<template>
  <div>
    <input type="file" ref="fileInput" accept=".xls,.xlsx" @change="handleFileChange" />
    <div class="table-container">
      <table v-if="tableData.length > 0" :style="{ fontSize: '10px' }" class="table-bg">
        <thead>
          <tr v-for="(row, rowIndex) in tableData.slice(0, 3)" :key="`header-${rowIndex}`" class="sticky-row">
            <td v-for="(cell, cellIndex) in row" :key="`${rowIndex}-${cellIndex}`">{{ cell }}</td>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in tableData.slice(3)" :key="rowIndex">
            <td v-for="(cell, cellIndex) in row" :key="`${rowIndex}-${cellIndex}`">{{ cell }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    <p v-if="tableData.length === 0 && initialTableData.length === 0">请上传Excel文件</p>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  name: 'ExcelUploader',
  data() {
    return {
      tableData: [], // 当前显示的表格数据
      initialTableData: [] // 初始表格数据备份，用于页面刷新后恢复
    };
  },
  mounted() {
    this.restoreTableData(); // 页面加载时尝试恢复数据
  },
  beforeRouteLeave(to, from, next) {
    // 页面离开前保存数据
    this.saveTableData();
    next();
  },
  methods: {
    handleFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        const binaryStr = e.target.result;
        const workbook = XLSX.read(binaryStr, { type: 'binary' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        let rawTableData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将第一列（索引为0）的数据转换为YYYY-MM-DD格式的日期
        rawTableData.forEach(row => {
          const dateValue = this.parseExcelDate(row[0]);
          if (dateValue) {
            row[0] = dateValue;
          }
        });

        this.tableData = rawTableData;
        this.initialTableData = [...this.tableData]; 
      };
      reader.readAsBinaryString(file);
    },
    parseExcelDate(dateStr) {
      const excelEpoch = new Date(Date.UTC(1899, 11, 30));
      const daysSinceEpoch = parseFloat(dateStr);
      if (isNaN(daysSinceEpoch)) return null;

      const dateObj = new Date(excelEpoch.getTime() + daysSinceEpoch * 24 * 60 * 60 * 1000);
      // 格式化日期为YYYY-MM-DD
      return `${dateObj.getFullYear()}-${('0' + (dateObj.getMonth() + 1)).slice(-2)}-${('0' + dateObj.getDate()).slice(-2)}`;
    },
    saveTableData() {
      localStorage.setItem('excelTableData', JSON.stringify(this.tableData));
    },
    restoreTableData() {
      const savedData = localStorage.getItem('excelTableData');
      if (savedData) {
        try {
          this.tableData = JSON.parse(savedData);
        } catch (error) {
          console.error('Failed to restore table data:', error);
        }
      }
    }
  }
};
</script>

<style scoped>
.table-container {
  max-height: 1000px;
  overflow-y: auto;
}

.table-bg {
  background-color: #ffffff;
  border-collapse: collapse;
  width: 100%;
}

.table-bg thead {
  position: sticky;
  top: 0; /* 距离顶部的距离，可根据需要调整 */
  background-color: white; 
  z-index: 1; /* 确保表头在其他内容之上 */
}

.table-bg td,
.sticky-row td {
  border: 1px solid #ddd;
  padding: 8px;
}
</style>